﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using JFnetcore.Models;
using Utility;
using Microsoft.AspNetCore.Http;
using static Utility.FileUtil;
using System.IO;
using System.Net.Http.Headers;
using static Utility.EnumUtil;
using System.Text;
using Newtonsoft.Json;
using Services.IService;
using Models;
using System.Linq.Expressions;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace JFnetcore.Controllers
{
    public class ProductController : BaseController
    {
        private IProductService _productService;
        private IProducttypeService _producttypeService;
        private ILogService _logService;
        private IVproductService _vproductService;
        public ProductController(IProductService productService, IProducttypeService producttypeService, ILogService logService, IVproductService vproductService)
        {
            _productService = productService;
            _producttypeService = producttypeService;
            _logService = logService;
            _vproductService = vproductService;
        }

        #region 软件中心

        #region 软件列表
        /// <summary>
        /// 打开产品下载列表视图
        /// </summary>
        /// <param name="pagemodel"></param>
        /// <returns></returns>
        public IActionResult List(PageModel pagemodel)
        {
            SessionModel userSession = getUserSession();
            if (userSession != null)
            {
                if (string.IsNullOrEmpty(pagemodel.PageCurrent))
                    pagemodel.PageCurrent = "1";
                if (string.IsNullOrEmpty(pagemodel.PageSize))
                    pagemodel.PageSize = "30";
                ViewBag.SearchKeyWords = pagemodel.SearchKeyWords;
                ViewBag.PageSize = pagemodel.PageSize;
                ViewBag.PageCurrent = pagemodel.PageCurrent;
                ViewBag.OrderField = string.IsNullOrEmpty(pagemodel.OrderField) ? "CreateTime" : pagemodel.OrderField;
                ViewBag.OrderDirection = pagemodel.OrderDirection;

                Expression<Func<VproductModel, bool>> where = LinqUtil.True<VproductModel>();
                where = where.AndAlso(i => i.ProductType_name.Contains(pagemodel.SearchKeyWords) || i.Product_name.Contains(pagemodel.SearchKeyWords) || i.Product_No.Contains(pagemodel.SearchKeyWords) || i.Product_txt.Contains(pagemodel.SearchKeyWords));
                ViewBag.AllRecords = _vproductService.GetList(where).Count;
                ViewBag.Modellist = _vproductService.GetPageList(where, int.Parse(pagemodel.PageCurrent), int.Parse(pagemodel.PageSize), pagemodel.OrderField);
                return View();

            }
            else
                return Content(ReturnJsonHelp.BJUIajaxJson(301, "Session超时！", "", "", "", false, "", ""));
        }

        #endregion

        #region 类型管理
        /// <summary>
        /// 打开产品类型列表视图
        /// </summary>
        /// <param name="pagemodel"></param>
        /// <returns></returns>
        public IActionResult Type(PageModel pagemodel)
        {
            SessionModel userSession = getUserSession();
            if (userSession != null)
            {
                if (string.IsNullOrEmpty(pagemodel.PageCurrent))
                    pagemodel.PageCurrent = "1";
                if (string.IsNullOrEmpty(pagemodel.PageSize))
                    pagemodel.PageSize = "30";
                ViewBag.SearchKeyWords = pagemodel.SearchKeyWords;
                ViewBag.PageSize = pagemodel.PageSize;
                ViewBag.PageCurrent = pagemodel.PageCurrent;
                ViewBag.OrderField = string.IsNullOrEmpty(pagemodel.OrderField) ? "CreateTime" : pagemodel.OrderField;
                ViewBag.OrderDirection = pagemodel.OrderDirection;

                Expression<Func<ProducttypeModel, bool>> where = LinqUtil.True<ProducttypeModel>();
                where = where.AndAlso(i => i.ProductType_name.Contains(pagemodel.SearchKeyWords));
                ViewBag.AllRecords = _producttypeService.GetList(where).Count;
                ViewBag.Modellist = _producttypeService.GetPageList(where, int.Parse(pagemodel.PageCurrent), int.Parse(pagemodel.PageSize), pagemodel.OrderField);

                return View();
            }
            else
                return Content(ReturnJsonHelp.BJUIajaxJson(301, "Session超时！", "", "", "", false, "", ""));

        }


        /// <summary>
        /// 打开产品类型编辑视图
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IActionResult TypeEdit(string id)
        {
            SessionModel userSession = getUserSession();
            if (userSession != null)
            {
                if (string.IsNullOrEmpty(id))
                {
                    return View();
                }
                else
                {
                    var model = _producttypeService.GetById(Int32.Parse(id));
                    return View(model);
                }
            }
            else
                return Content(ReturnJsonHelp.BJUIajaxJson(301, "Session超时！", "", "", "", false, "", ""));

        }

        /// <summary>
        /// 表单提交产品类型编辑接口
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("ProductTypeEdit")]
        public IActionResult ProductEdit(ProducttypeModel model)
        {
            SessionModel sm = getUserSession();
            if (sm != null)
            {
                model.Createtime = DateTime.Now;
                if (model.Id != 0)
                {
                    if (_producttypeService.Update(model))
                    {
                        _logService.Add(DateTime.Now, sm.IP, sm.User.Id.ToString(), (int)OperationEnum.update, "修改产品类型 " + model.ProductType_name);
                        return Content(ReturnJsonHelp.BJUIajaxJson(200, "修改产品类型 " + model.ProductType_name + " 成功！", "ProductType", "", "", true, "", ""));
                    }
                    else
                    {
                        return Content(ReturnJsonHelp.BJUIajaxJson(300, "修改产品类型 " + model.ProductType_name + " 失败！", "", "", "", false, "", ""));
                    }
                }
                else
                {
                    if (_producttypeService.Insert(model) > 0)
                    {
                        _logService.Add(DateTime.Now, sm.IP, sm.User.Id.ToString(), (int)OperationEnum.add, "新增产品类型 " + model.ProductType_name);
                        return Content(ReturnJsonHelp.BJUIajaxJson(200, "新增产品类型 " + model.ProductType_name + " 成功！", "ProductType", "", "", true, "", ""));
                    }
                    else
                    {
                        return Content(ReturnJsonHelp.BJUIajaxJson(300, "新增产品类型 " + model.ProductType_name + " 失败！", "", "", "", false, "", ""));
                    }
                }
            }
            else
                return Content(ReturnJsonHelp.BJUIajaxJson(301, "Session超时！", "", "", "", false, "", ""));
        }

        public IActionResult TypeDelete(string id)
        {
            SessionModel sm = getUserSession();
            if (sm != null)
            {
                if (_productService.GetList().Where(i => i.ProductType_Id == Int32.Parse(id)).Count() > 0)
                {
                    return Content(ReturnJsonHelp.BJUIajaxJson(300, "删除失败, 该类型下有产品！", "", "", "", false, "", ""));
                }
                else
                {
                    string name = _producttypeService.GetById(int.Parse(id)).ProductType_name;
                    if (_producttypeService.DeleteById(int.Parse(id)))
                    {
                        _logService.Add(DateTime.Now, sm.IP, sm.User.Id.ToString(), (int)OperationEnum.delete, "删除产品类型 " + name);

                        return Content(ReturnJsonHelp.BJUIajaxJson(200, "删除成功！", "ProductType", "", "", false, "", ""));
                    }
                    else
                    {
                        return Content(ReturnJsonHelp.BJUIajaxJson(300, "删除失败！", "", "", "", false, "", ""));
                    }
                }
            }
            else
                return Content(ReturnJsonHelp.BJUIajaxJson(301, "Session超时！", "", "", "", false, "", ""));
        }
        #endregion

        #region 软件管理
        /// <summary>
        /// 打开产品管理列表视图
        /// </summary>
        /// <param name="pagemodel"></param>
        /// <returns></returns>
        public IActionResult Index(PageModel pagemodel)
        {
            SessionModel sm = getUserSession();
            if (sm != null)
            {
                if (string.IsNullOrEmpty(pagemodel.PageCurrent))
                    pagemodel.PageCurrent = "1";
                if (string.IsNullOrEmpty(pagemodel.PageSize))
                    pagemodel.PageSize = "30";
                ViewBag.SearchKeyWords = pagemodel.SearchKeyWords;
                ViewBag.PageSize = pagemodel.PageSize;
                ViewBag.PageCurrent = pagemodel.PageCurrent;
                ViewBag.OrderField = string.IsNullOrEmpty(pagemodel.OrderField) ? "CreateTime" : pagemodel.OrderField;
                ViewBag.OrderDirection = pagemodel.OrderDirection;

                Expression<Func<VproductModel, bool>> where = LinqUtil.True<VproductModel>();
                where = where.AndAlso(i => i.ProductType_name.Contains(pagemodel.SearchKeyWords) || i.Product_name.Contains(pagemodel.SearchKeyWords) || i.Product_No.Contains(pagemodel.SearchKeyWords) || i.Product_txt.Contains(pagemodel.SearchKeyWords));
                ViewBag.AllRecords = _vproductService.GetList(where).Count;
                ViewBag.Modellist = _vproductService.GetPageList(where, int.Parse(pagemodel.PageCurrent), int.Parse(pagemodel.PageSize), pagemodel.OrderField);
                return View();
            }
            else
                return Content(ReturnJsonHelp.BJUIajaxJson(301, "Session超时！", "", "", "", false, "", ""));

        }

        /// <summary>
        /// 打开产品编辑视图
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IActionResult Edit(string id)
        {
            SessionModel sm = getUserSession();
            if (sm != null)
            {
                if (string.IsNullOrEmpty(id))
                {
                    return View();
                }
                else
                {
                    var model = _productService.GetById(Int32.Parse(id));
                    return View(model);
                }
            }
            else
                return Content(ReturnJsonHelp.BJUIajaxJson(301, "Session超时！", "", "", "", false, "", ""));

        }

        /// <summary>
        /// 打开上传视图
        /// </summary>
        /// <returns></returns>
        public IActionResult Upload()
        {
            SessionModel sm = getUserSession();
            if (sm != null)
                return View();
            else
                return Content(ReturnJsonHelp.BJUIajaxJson(301, "Session超时！", "", "", "", false, "", ""));
        }

        /// <summary>
        /// 上传接口
        /// </summary>
        /// <param name="files"></param>
        /// <returns></returns>
        [HttpPost("UploadFiles")]
        public IActionResult UploadFiles(IList<IFormFile> files)
        {
            SessionModel sm = getUserSession();
            if (sm != null)
            {
                try
                {
                    string logrenark = "";
                    long size = 0;

                    foreach (var file in files)
                    {
                        var filename = ContentDispositionHeaderValue
                                        .Parse(file.ContentDisposition)
                                        .FileName
                                        .Trim('"');
                        filename = filename.Substring(filename.LastIndexOf('\\') + 1);
                        logrenark += filename + ",";
                        filename = System.IO.Directory.GetCurrentDirectory() + "/wwwroot/upload/" + filename;
                        size += file.Length;
                        using (FileStream fs = System.IO.File.Create(filename))
                        {
                            file.CopyTo(fs);
                            fs.Flush();
                        }
                    }

                    _logService.Add(DateTime.Now, sm.IP, sm.User.Id.ToString(), (int)OperationEnum.upload, "上传文件" + logrenark);

                    return Content(ReturnJsonHelp.BJUIajaxJson(200, "上传成功！", "", "", "", false, "", ""));
                }
                catch (Exception e)
                {
                    return Content(ReturnJsonHelp.BJUIajaxJson(300, "提交失败！ [" + e.Message + "]", "", "", "", false, "", ""));
                }
            }
            else
                return Content(ReturnJsonHelp.BJUIajaxJson(301, "Session超时！", "", "", "", false, "", ""));
        }

        /// <summary>
        /// 表单提交产品编辑接口
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("ProductEdit")]
        public IActionResult ProductEdit(ProductModel model)
        {
            SessionModel sm = getUserSession();
            if (sm != null)
            {
                model.Createtime = DateTime.Now;
                if (model.Id != 0)
                {
                    if (_productService.Update(model))
                    {
                        _logService.Add(DateTime.Now, sm.IP, sm.User.Id.ToString(), (int)OperationEnum.update, "修改产品 " + model.Product_name);
                        return Content(ReturnJsonHelp.BJUIajaxJson(200, "修改产品 " + model.Product_name + " 成功！", "ProductIndex", "", "", true, "", ""));
                    }
                    else
                    {
                        return Content(ReturnJsonHelp.BJUIajaxJson(300, "修改产品 " + model.Product_name + " 失败！", "", "", "", false, "", ""));
                    }
                }
                else
                {
                    if (_productService.Insert(model) > 0)
                    {
                        _logService.Add(DateTime.Now, sm.IP, sm.User.Id.ToString(), (int)OperationEnum.add, "新增产品 " + model.Product_name);
                        return Content(ReturnJsonHelp.BJUIajaxJson(200, "新增产品 " + model.Product_name + " 成功！", "ProductIndex", "", "", true, "", ""));
                    }
                    else
                    {
                        return Content(ReturnJsonHelp.BJUIajaxJson(300, "新增产品 " + model.Product_name + " 失败！", "", "", "", false, "", ""));
                    }
                }
            }
            else
                return Content(ReturnJsonHelp.BJUIajaxJson(301, "Session超时！", "", "", "", false, "", ""));
        }

        /// <summary>
        /// 按钮提交删除接口
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IActionResult ProductDelete(string id)
        {
            SessionModel sm = getUserSession();
            if (sm != null)
            {
                string name = _productService.GetById(int.Parse(id)).Product_name;
                if (_productService.DeleteById(int.Parse(id)))
                {
                    _logService.Add(DateTime.Now, sm.IP, sm.User.Id.ToString(), (int)OperationEnum.delete, "删除产品" + name);

                    return Content(ReturnJsonHelp.BJUIajaxJson(200, "删除成功！", "ProductIndex", "", "", false, "", ""));
                }
                else
                {
                    return Content(ReturnJsonHelp.BJUIajaxJson(300, "删除失败！", "", "", "", false, "", ""));
                }
            }
            else
                return Content(ReturnJsonHelp.BJUIajaxJson(301, "Session超时！", "", "", "", false, "", ""));
        }

        /// <summary>
        /// 打开上传文件选择视图
        /// </summary>
        /// <returns></returns>
        public IActionResult search()
        {
            SessionModel sm = getUserSession();
            if (sm != null)
            {
                string jsonstr = "";
                List<fileinfoModel> list = FileUtil.FindFile("wwwroot//upload");
                int i = 0;
                foreach (fileinfoModel m in list)
                {
                    jsonstr += "{\"Product_url\":\"" + m.name + "\", \"uploadurl\":\"/wwwroot/upload/" + m.name + "\", \"date\":\"" + m.createtime.ToString("yyyy-MM-dd HH:mm:ss") + "\"},";
                    i++;
                }
                if (i > 0)
                    return Content("[" + jsonstr.Remove(jsonstr.Length - 1) + "]");
                else
                    return Content("[]");
            }
            else
                return Content(ReturnJsonHelp.BJUIajaxJson(301, "Session超时！", "", "", "", false, "", ""));
        }

        /// <summary>
        /// 获取类型Json
        /// </summary>
        /// <returns></returns>
        public IActionResult SearchType()
        {
            SessionModel sm = getUserSession();
            if (sm != null)
            {
                StringBuilder resultstr = new StringBuilder();
                List<ProducttypeModel> list = _producttypeService.GetList().Where(i => i.Disable == 1).ToList();
                resultstr.Append("[");
                int y = 0;
                foreach (ProducttypeModel a in list)
                {
                    resultstr.Append("{\"ProductType_Id\":\"" + a.Id + "\",\"ProductType_name\":\"" + a.ProductType_name + "\"},");
                    y++;
                }
                if (y > 0)
                    resultstr.Remove(resultstr.ToString().LastIndexOf(','), 1);
                resultstr.Append("]");
                return Content(resultstr.ToString());
            }
            else
                return Content(ReturnJsonHelp.BJUIajaxJson(301, "Session超时！", "", "", "", false, "", ""));
        }
        #endregion

        #endregion
        
    }
}
